package com.foftact.etfposi;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * ETF持仓明细控制器
 * 处理ETF持仓相关的HTTP请求
 */
@RestController
@RequestMapping("/api/etf/position")
public class ETFPosiationController {
    private static final Logger logger = LoggerFactory.getLogger(ETFPosiationController.class);

    @Autowired
    private ETFPosiationService etfPosiationService;

    /**
     * 抓取并保存ETF持仓数据
     * @param fundCode 基金代码
     * @return 操作结果
     */
    @GetMapping("/fetch/{fundCode}")
    public Map<String, Object> fetchAndSaveETFPosiationData(@PathVariable String fundCode) {
        Map<String, Object> result = new HashMap<>();
        try {
            logger.info("收到抓取ETF持仓数据的请求，fundCode: {}", fundCode);
            int savedCount = etfPosiationService.fetchAndSaveETFPosiationData(fundCode);
            result.put("success", true);
            result.put("message", "ETF持仓数据抓取成功");
            result.put("data", savedCount);
        } catch (Exception e) {
            logger.error("抓取ETF持仓数据失败，fundCode: {}", fundCode, e);
            result.put("success", false);
            result.put("message", "ETF持仓数据抓取失败：" + e.getMessage());
        }
        return result;
    }

    /**
     * 根据基金代码、年份和季度获取持仓数据
     * @param fundCode 基金代码
     * @param reportYear 报告年份
     * @param reportQuarter 报告季度
     * @return 持仓数据列表
     */
    @GetMapping("/get")
    public Map<String, Object> getETFPosiationByFundCodeAndReportPeriod(
            @RequestParam String fundCode,
            @RequestParam(required = false) Integer reportYear,
            @RequestParam(required = false) Integer reportQuarter) {
        Map<String, Object> result = new HashMap<>();
        try {
            logger.info("收到获取ETF持仓数据的请求，fundCode: {}, reportYear: {}, reportQuarter: {}", 
                        fundCode, reportYear, reportQuarter);
            List<ETFPosiation> etfPosiationList = etfPosiationService.getETFPosiationByFundCodeAndReportPeriod(
                    fundCode, reportYear, reportQuarter);
            result.put("success", true);
            result.put("message", "ETF持仓数据查询成功");
            result.put("data", etfPosiationList);
        } catch (Exception e) {
            logger.error("获取ETF持仓数据失败", e);
            result.put("success", false);
            result.put("message", "ETF持仓数据查询失败：" + e.getMessage());
        }
        return result;
    }

    /**
     * 获取指定基金近2年的持仓数据
     * @param fundCode 基金代码
     * @return 持仓数据列表
     */
    @GetMapping("/recent/{fundCode}")
    public Map<String, Object> getRecentTwoYearsETFPosiationByFundCode(@PathVariable String fundCode) {
        Map<String, Object> result = new HashMap<>();
        try {
            logger.info("收到获取ETF近2年持仓数据的请求，fundCode: {}", fundCode);
            List<ETFPosiation> etfPosiationList = etfPosiationService.getRecentTwoYearsETFPosiationByFundCode(fundCode);
            result.put("success", true);
            result.put("message", "ETF近2年持仓数据查询成功");
            result.put("data", etfPosiationList);
        } catch (Exception e) {
            logger.error("获取ETF近2年持仓数据失败", e);
            result.put("success", false);
            result.put("message", "ETF近2年持仓数据查询失败：" + e.getMessage());
        }
        return result;
    }

    /**
     * 保存单个ETF持仓数据
     * @param etfPosiation ETF持仓数据对象
     * @return 操作结果
     */
    @PostMapping("/save")
    public Map<String, Object> saveETFPosiation(@RequestBody ETFPosiation etfPosiation) {
        Map<String, Object> result = new HashMap<>();
        try {
            logger.info("收到保存ETF持仓数据的请求");
            boolean saved = etfPosiationService.saveETFPosiation(etfPosiation);
            if (saved) {
                result.put("success", true);
                result.put("message", "ETF持仓数据保存成功");
            } else {
                result.put("success", false);
                result.put("message", "ETF持仓数据保存失败");
            }
        } catch (Exception e) {
            logger.error("保存ETF持仓数据失败", e);
            result.put("success", false);
            result.put("message", "ETF持仓数据保存失败：" + e.getMessage());
        }
        return result;
    }

    /**
     * 更新ETF持仓数据
     * @param etfPosiation ETF持仓数据对象
     * @return 操作结果
     */
    @PutMapping("/update")
    public Map<String, Object> updateETFPosiation(@RequestBody ETFPosiation etfPosiation) {
        Map<String, Object> result = new HashMap<>();
        try {
            logger.info("收到更新ETF持仓数据的请求");
            boolean updated = etfPosiationService.updateETFPosiation(etfPosiation);
            if (updated) {
                result.put("success", true);
                result.put("message", "ETF持仓数据更新成功");
            } else {
                result.put("success", false);
                result.put("message", "ETF持仓数据更新失败");
            }
        } catch (Exception e) {
            logger.error("更新ETF持仓数据失败", e);
            result.put("success", false);
            result.put("message", "ETF持仓数据更新失败：" + e.getMessage());
        }
        return result;
    }

    /**
     * 根据基金代码删除持仓数据
     * @param fundCode 基金代码
     * @return 操作结果
     */
    @DeleteMapping("/delete/{fundCode}")
    public Map<String, Object> deleteETFPosiationByFundCode(@PathVariable String fundCode) {
        Map<String, Object> result = new HashMap<>();
        try {
            logger.info("收到删除ETF持仓数据的请求，fundCode: {}", fundCode);
            boolean deleted = etfPosiationService.deleteETFPosiationByFundCode(fundCode);
            if (deleted) {
                result.put("success", true);
                result.put("message", "ETF持仓数据删除成功");
            } else {
                result.put("success", false);
                result.put("message", "ETF持仓数据删除失败");
            }
        } catch (Exception e) {
            logger.error("删除ETF持仓数据失败", e);
            result.put("success", false);
            result.put("message", "ETF持仓数据删除失败：" + e.getMessage());
        }
        return result;
    }

    /**
     * 根据基金代码、年份和季度删除持仓数据
     * @param fundCode 基金代码
     * @param reportYear 报告年份
     * @param reportQuarter 报告季度
     * @return 操作结果
     */
    @DeleteMapping("/delete")
    public Map<String, Object> deleteETFPosiationByFundCodeAndReportPeriod(
            @RequestParam String fundCode,
            @RequestParam Integer reportYear,
            @RequestParam Integer reportQuarter) {
        Map<String, Object> result = new HashMap<>();
        try {
            logger.info("收到删除ETF持仓数据的请求，fundCode: {}, reportYear: {}, reportQuarter: {}", 
                        fundCode, reportYear, reportQuarter);
            boolean deleted = etfPosiationService.deleteETFPosiationByFundCodeAndReportPeriod(
                    fundCode, reportYear, reportQuarter);
            if (deleted) {
                result.put("success", true);
                result.put("message", "ETF持仓数据删除成功");
            } else {
                result.put("success", false);
                result.put("message", "ETF持仓数据删除失败");
            }
        } catch (Exception e) {
            logger.error("删除ETF持仓数据失败", e);
            result.put("success", false);
            result.put("message", "ETF持仓数据删除失败：" + e.getMessage());
        }
        return result;
    }

    /**
     * 清空ETF持仓表
     * @return 操作结果
     */
    @DeleteMapping("/clear")
    public Map<String, Object> clearETFPosiation() {
        Map<String, Object> result = new HashMap<>();
        try {
            logger.info("收到清空ETF持仓表的请求");
            boolean cleared = etfPosiationService.clearETFPosiation();
            if (cleared) {
                result.put("success", true);
                result.put("message", "ETF持仓表清空成功");
            } else {
                result.put("success", false);
                result.put("message", "ETF持仓表清空失败");
            }
        } catch (Exception e) {
            logger.error("清空ETF持仓表失败", e);
            result.put("success", false);
            result.put("message", "ETF持仓表清空失败：" + e.getMessage());
        }
        return result;
    }
}